"""
教学质量评估AI系统服务
实现教师授课行为分析、师生互动评估和教学风格优化
"""
import asyncio
import logging
import numpy as np
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Tuple, Any
from uuid import uuid4
import time
from collections import defaultdict, deque
import json
from enum import Enum
import cv2

logger = logging.getLogger(__name__)


class TeachingBehavior(str, Enum):
    """教学行为类型枚举"""
    LECTURING = "lecturing"              # 讲解
    WRITING_BOARD = "writing_board"      # 板书
    DEMONSTRATING = "demonstrating"      # 演示
    QUESTIONING = "questioning"          # 提问
    ANSWERING = "answering"              # 回答
    WALKING = "walking"                  # 走动
    GESTURING = "gesturing"              # 手势
    INTERACTING = "interacting"          # 互动
    OBSERVING = "observing"              # 观察
    RESTING = "resting"                  # 休息


class TeachingStyle(str, Enum):
    """教学风格枚举"""
    AUTHORITATIVE = "authoritative"      # 权威型
    INTERACTIVE = "interactive"          # 互动型
    DEMONSTRATIVE = "demonstrative"      # 演示型
    COLLABORATIVE = "collaborative"      # 协作型
    INQUIRY_BASED = "inquiry_based"      # 探究型
    MIXED = "mixed"                      # 混合型


class FatigueLevel(str, Enum):
    """疲劳度等级枚举"""
    VERY_LOW = "very_low"        # 非常清醒
    LOW = "low"                  # 轻微疲劳
    MEDIUM = "medium"            # 中等疲劳
    HIGH = "high"                # 较为疲劳
    VERY_HIGH = "very_high"      # 非常疲劳


class InteractionQuality(str, Enum):
    """互动质量等级枚举"""
    EXCELLENT = "excellent"      # 优秀
    GOOD = "good"               # 良好
    AVERAGE = "average"         # 一般
    POOR = "poor"               # 较差
    VERY_POOR = "very_poor"     # 很差


class TeacherBehaviorData:
    """教师行为数据"""
    def __init__(self, teacher_id: str, timestamp: datetime, behavior: TeachingBehavior,
                 gesture_data: Dict[str, Any], facial_expression: Dict[str, float],
                 movement_data: Dict[str, Any], voice_features: Dict[str, float],
                 fatigue_level: FatigueLevel, confidence: float):
        self.teacher_id = teacher_id
        self.timestamp = timestamp
        self.behavior = behavior
        self.gesture_data = gesture_data
        self.facial_expression = facial_expression
        self.movement_data = movement_data
        self.voice_features = voice_features
        self.fatigue_level = fatigue_level
        self.confidence = confidence


class InteractionData:
    """师生互动数据"""
    def __init__(self, interaction_id: str, teacher_id: str, timestamp: datetime,
                 interaction_type: str, duration: float, student_response_count: int,
                 teacher_question_count: int, interaction_quality: InteractionQuality,
                 engagement_score: float, effectiveness_score: float):
        self.interaction_id = interaction_id
        self.teacher_id = teacher_id
        self.timestamp = timestamp
        self.interaction_type = interaction_type
        self.duration = duration
        self.student_response_count = student_response_count
        self.teacher_question_count = teacher_question_count
        self.interaction_quality = interaction_quality
        self.engagement_score = engagement_score
        self.effectiveness_score = effectiveness_score


class TeachingStyleAnalysis:
    """教学风格分析结果"""
    def __init__(self, analysis_id: str, teacher_id: str, teaching_style: TeachingStyle,
                 style_confidence: float, behavior_distribution: Dict[str, float],
                 interaction_patterns: Dict[str, Any], strengths: List[str],
                 improvement_areas: List[str], recommendations: List[str]):
        self.analysis_id = analysis_id
        self.teacher_id = teacher_id
        self.teaching_style = teaching_style
        self.style_confidence = style_confidence
        self.behavior_distribution = behavior_distribution
        self.interaction_patterns = interaction_patterns
        self.strengths = strengths
        self.improvement_areas = improvement_areas
        self.recommendations = recommendations


class TeachingQualityReport:
    """教学质量报告"""
    def __init__(self, report_id: str, teacher_id: str, classroom_id: str,
                 analysis_period: Tuple[datetime, datetime], overall_score: float,
                 behavior_analysis: Dict[str, Any], interaction_analysis: Dict[str, Any],
                 style_analysis: TeachingStyleAnalysis, fatigue_analysis: Dict[str, Any],
                 improvement_suggestions: List[str], generated_at: datetime):
        self.report_id = report_id
        self.teacher_id = teacher_id
        self.classroom_id = classroom_id
        self.analysis_period = analysis_period
        self.overall_score = overall_score
        self.behavior_analysis = behavior_analysis
        self.interaction_analysis = interaction_analysis
        self.style_analysis = style_analysis
        self.fatigue_analysis = fatigue_analysis
        self.improvement_suggestions = improvement_suggestions
        self.generated_at = generated_at


class TeacherBehaviorAnalyzer:
    """教师行为分析器"""
    
    def __init__(self):
        self.gesture_detector = None  # 手势检测器
        self.face_analyzer = None     # 面部表情分析器
        self.pose_detector = None     # 姿态检测器
        
        # 行为权重配置
        self.behavior_weights = {
            'gesture': 0.3,      # 手势权重
            'expression': 0.2,   # 表情权重
            'movement': 0.3,     # 动作权重
            'voice': 0.2         # 语音权重
        }
    
    async def analyze_teacher_behavior(self, image: np.ndarray, teacher_bbox: Tuple[int, int, int, int],
                                     teacher_id: str, audio_features: Optional[Dict[str, Any]] = None) -> TeacherBehaviorData:
        """分析教师行为"""
        timestamp = datetime.now()
        
        # 提取教师区域
        x, y, w, h = teacher_bbox
        teacher_roi = image[y:y+h, x:x+w]
        
        # 分析手势
        gesture_data = await self._analyze_gestures(teacher_roi)
        
        # 分析面部表情
        facial_expression = await self._analyze_facial_expression(teacher_roi)
        
        # 分析动作和移动
        movement_data = await self._analyze_movement(teacher_roi)
        
        # 分析语音特征
        voice_features = self._analyze_voice_features(audio_features) if audio_features else {}
        
        # 识别教学行为
        behavior = await self._recognize_teaching_behavior(
            gesture_data, facial_expression, movement_data, voice_features
        )
        
        # 评估疲劳度
        fatigue_level = self._assess_fatigue_level(facial_expression, voice_features, movement_data)
        
        # 计算置信度
        confidence = self._calculate_confidence(gesture_data, facial_expression, movement_data)
        
        return TeacherBehaviorData(
            teacher_id=teacher_id,
            timestamp=timestamp,
            behavior=behavior,
            gesture_data=gesture_data,
            facial_expression=facial_expression,
            movement_data=movement_data,
            voice_features=voice_features,
            fatigue_level=fatigue_level,
            confidence=confidence
        )
    
    async def _analyze_gestures(self, roi: np.ndarray) -> Dict[str, Any]:
        """分析手势"""
        # 模拟手势分析
        # 实际实现中会使用手势识别模型
        
        gesture_types = ['pointing', 'explaining', 'demonstrating', 'writing', 'neutral']
        gesture_type = np.random.choice(gesture_types)
        
        # 手势强度和频率
        gesture_intensity = np.random.uniform(0.3, 1.0)
        gesture_frequency = np.random.uniform(0.1, 0.8)
        
        # 手势位置（相对于身体）
        gesture_position = {
            'left_hand': np.random.uniform(0, 1),
            'right_hand': np.random.uniform(0, 1),
            'both_hands': np.random.uniform(0, 1)
        }
        
        return {
            'gesture_type': gesture_type,
            'intensity': gesture_intensity,
            'frequency': gesture_frequency,
            'position': gesture_position,
            'is_expressive': gesture_intensity > 0.6
        }
    
    async def _analyze_facial_expression(self, roi: np.ndarray) -> Dict[str, float]:
        """分析面部表情"""
        # 模拟面部表情分析
        # 实际实现中会使用面部表情识别模型
        
        expressions = {
            'happy': np.random.uniform(0, 0.8),
            'neutral': np.random.uniform(0.2, 0.9),
            'focused': np.random.uniform(0.3, 0.9),
            'tired': np.random.uniform(0, 0.6),
            'stressed': np.random.uniform(0, 0.4),
            'engaged': np.random.uniform(0.4, 1.0)
        }
        
        # 确保表情概率和为1
        total = sum(expressions.values())
        expressions = {k: v/total for k, v in expressions.items()}
        
        # 眼部特征
        eye_openness = np.random.uniform(0.6, 1.0)
        blink_rate = np.random.uniform(10, 25)  # 每分钟眨眼次数
        
        expressions.update({
            'eye_openness': eye_openness,
            'blink_rate': blink_rate,
            'alertness': (eye_openness + (25 - blink_rate) / 15) / 2
        })
        
        return expressions
    
    async def _analyze_movement(self, roi: np.ndarray) -> Dict[str, Any]:
        """分析动作和移动"""
        # 模拟动作分析
        # 实际实现中会使用姿态估计和动作识别
        
        # 身体姿态
        posture_score = np.random.uniform(0.5, 1.0)
        
        # 移动模式
        movement_patterns = ['stationary', 'walking', 'pacing', 'gesturing']
        movement_pattern = np.random.choice(movement_patterns)
        
        # 移动频率和范围
        movement_frequency = np.random.uniform(0.1, 0.7)
        movement_range = np.random.uniform(0.2, 1.0)
        
        # 身体朝向
        body_orientation = {
            'facing_students': np.random.uniform(0.6, 1.0),
            'facing_board': np.random.uniform(0, 0.4),
            'profile': np.random.uniform(0, 0.3)
        }
        
        return {
            'posture_score': posture_score,
            'movement_pattern': movement_pattern,
            'movement_frequency': movement_frequency,
            'movement_range': movement_range,
            'body_orientation': body_orientation,
            'is_dynamic': movement_frequency > 0.4
        }
    
    def _analyze_voice_features(self, audio_features: Dict[str, Any]) -> Dict[str, float]:
        """分析语音特征"""
        if not audio_features:
            return {}
        
        # 从音频特征中提取教学相关信息
        voice_features = {
            'volume': audio_features.get('volume', np.random.uniform(0.4, 0.8)),
            'pitch': audio_features.get('pitch', np.random.uniform(0.3, 0.7)),
            'clarity': audio_features.get('clarity', np.random.uniform(0.6, 0.9)),
            'pace': audio_features.get('pace', np.random.uniform(0.4, 0.8)),
            'enthusiasm': audio_features.get('enthusiasm', np.random.uniform(0.3, 0.9))
        }
        
        # 计算语音质量分数
        voice_quality = np.mean([
            voice_features['volume'],
            voice_features['clarity'],
            voice_features['pace']
        ])
        
        voice_features['voice_quality'] = voice_quality
        
        return voice_features
    
    async def _recognize_teaching_behavior(self, gesture_data: Dict[str, Any], 
                                         facial_expression: Dict[str, float],
                                         movement_data: Dict[str, Any],
                                         voice_features: Dict[str, float]) -> TeachingBehavior:
        """识别教学行为"""
        # 基于多模态特征识别教学行为
        
        # 手势特征
        gesture_type = gesture_data.get('gesture_type', 'neutral')
        gesture_intensity = gesture_data.get('intensity', 0.5)
        
        # 动作特征
        movement_pattern = movement_data.get('movement_pattern', 'stationary')
        body_orientation = movement_data.get('body_orientation', {})
        
        # 语音特征
        voice_volume = voice_features.get('volume', 0.5)
        voice_enthusiasm = voice_features.get('enthusiasm', 0.5)
        
        # 行为识别逻辑
        if gesture_type == 'writing' or body_orientation.get('facing_board', 0) > 0.7:
            return TeachingBehavior.WRITING_BOARD
        elif gesture_type == 'pointing' and voice_volume > 0.6:
            return TeachingBehavior.QUESTIONING
        elif gesture_type == 'demonstrating':
            return TeachingBehavior.DEMONSTRATING
        elif movement_pattern == 'walking' and gesture_intensity > 0.5:
            return TeachingBehavior.INTERACTING
        elif gesture_type == 'explaining' and voice_enthusiasm > 0.6:
            return TeachingBehavior.LECTURING
        elif movement_pattern == 'stationary' and gesture_intensity < 0.3:
            return TeachingBehavior.OBSERVING
        else:
            # 默认根据概率选择
            behaviors = [
                TeachingBehavior.LECTURING,
                TeachingBehavior.QUESTIONING,
                TeachingBehavior.INTERACTING,
                TeachingBehavior.DEMONSTRATING,
                TeachingBehavior.OBSERVING
            ]
            weights = [0.3, 0.2, 0.2, 0.15, 0.15]
            return np.random.choice(behaviors, p=weights)
    
    def _assess_fatigue_level(self, facial_expression: Dict[str, float],
                            voice_features: Dict[str, float],
                            movement_data: Dict[str, Any]) -> FatigueLevel:
        """评估疲劳度"""
        # 基于多个指标评估疲劳度
        
        # 面部疲劳指标
        eye_openness = facial_expression.get('eye_openness', 0.8)
        tired_score = facial_expression.get('tired', 0.2)
        alertness = facial_expression.get('alertness', 0.7)
        
        # 语音疲劳指标
        voice_energy = voice_features.get('enthusiasm', 0.5)
        voice_clarity = voice_features.get('clarity', 0.8)
        
        # 动作疲劳指标
        movement_frequency = movement_data.get('movement_frequency', 0.5)
        posture_score = movement_data.get('posture_score', 0.8)
        
        # 综合疲劳分数
        fatigue_score = (
            (1 - eye_openness) * 0.25 +
            tired_score * 0.25 +
            (1 - alertness) * 0.2 +
            (1 - voice_energy) * 0.15 +
            (1 - voice_clarity) * 0.1 +
            (1 - movement_frequency) * 0.05
        )
        
        # 确定疲劳等级
        if fatigue_score < 0.2:
            return FatigueLevel.VERY_LOW
        elif fatigue_score < 0.4:
            return FatigueLevel.LOW
        elif fatigue_score < 0.6:
            return FatigueLevel.MEDIUM
        elif fatigue_score < 0.8:
            return FatigueLevel.HIGH
        else:
            return FatigueLevel.VERY_HIGH
    
    def _calculate_confidence(self, gesture_data: Dict[str, Any],
                            facial_expression: Dict[str, float],
                            movement_data: Dict[str, Any]) -> float:
        """计算检测置信度"""
        # 基于各模态的检测质量计算置信度
        
        gesture_confidence = gesture_data.get('intensity', 0.5)
        expression_confidence = max(facial_expression.values()) if facial_expression else 0.5
        movement_confidence = movement_data.get('posture_score', 0.5)
        
        overall_confidence = (
            gesture_confidence * 0.4 +
            expression_confidence * 0.3 +
            movement_confidence * 0.3
        )
        
        return min(1.0, max(0.0, overall_confidence))


class InteractionAnalyzer:
    """师生互动分析器"""
    
    def __init__(self):
        self.interaction_history = defaultdict(list)
        self.question_tracker = defaultdict(int)
        self.response_tracker = defaultdict(int)
    
    async def analyze_interaction(self, teacher_id: str, teacher_behavior: TeacherBehaviorData,
                                student_attention_data: List[Any],
                                audio_features: Optional[Dict[str, Any]] = None) -> InteractionData:
        """分析师生互动"""
        interaction_id = str(uuid4())
        timestamp = datetime.now()
        
        # 识别互动类型
        interaction_type = self._identify_interaction_type(teacher_behavior, audio_features)
        
        # 计算互动持续时间
        duration = self._calculate_interaction_duration(teacher_behavior, interaction_type)
        
        # 统计学生响应
        student_response_count = self._count_student_responses(student_attention_data)
        
        # 统计教师提问
        teacher_question_count = self._count_teacher_questions(teacher_behavior, audio_features)
        
        # 评估互动质量
        interaction_quality = self._assess_interaction_quality(
            teacher_behavior, student_attention_data, duration
        )
        
        # 计算参与度分数
        engagement_score = self._calculate_engagement_score(
            student_attention_data, student_response_count
        )
        
        # 计算有效性分数
        effectiveness_score = self._calculate_effectiveness_score(
            interaction_quality, engagement_score, duration
        )
        
        # 更新跟踪器
        self._update_trackers(teacher_id, interaction_type, teacher_question_count, student_response_count)
        
        interaction_data = InteractionData(
            interaction_id=interaction_id,
            teacher_id=teacher_id,
            timestamp=timestamp,
            interaction_type=interaction_type,
            duration=duration,
            student_response_count=student_response_count,
            teacher_question_count=teacher_question_count,
            interaction_quality=interaction_quality,
            engagement_score=engagement_score,
            effectiveness_score=effectiveness_score
        )
        
        # 存储互动历史
        self.interaction_history[teacher_id].append(interaction_data)
        
        return interaction_data
    
    def _identify_interaction_type(self, teacher_behavior: TeacherBehaviorData,
                                 audio_features: Optional[Dict[str, Any]]) -> str:
        """识别互动类型"""
        behavior = teacher_behavior.behavior
        voice_features = teacher_behavior.voice_features
        
        # 基于教师行为和语音特征识别互动类型
        if behavior == TeachingBehavior.QUESTIONING:
            return "question_answer"
        elif behavior == TeachingBehavior.DEMONSTRATING:
            return "demonstration"
        elif behavior == TeachingBehavior.INTERACTING:
            return "discussion"
        elif behavior == TeachingBehavior.LECTURING and voice_features.get('enthusiasm', 0) > 0.7:
            return "engaging_lecture"
        elif behavior == TeachingBehavior.OBSERVING:
            return "observation"
        else:
            return "general_interaction"
    
    def _calculate_interaction_duration(self, teacher_behavior: TeacherBehaviorData, 
                                      interaction_type: str) -> float:
        """计算互动持续时间"""
        # 基于互动类型估算持续时间
        base_durations = {
            "question_answer": 30.0,      # 30秒
            "demonstration": 120.0,       # 2分钟
            "discussion": 180.0,          # 3分钟
            "engaging_lecture": 300.0,    # 5分钟
            "observation": 60.0,          # 1分钟
            "general_interaction": 90.0   # 1.5分钟
        }
        
        base_duration = base_durations.get(interaction_type, 60.0)
        
        # 根据教师行为特征调整时长
        gesture_intensity = teacher_behavior.gesture_data.get('intensity', 0.5)
        voice_enthusiasm = teacher_behavior.voice_features.get('enthusiasm', 0.5)
        
        duration_multiplier = (gesture_intensity + voice_enthusiasm) / 2
        actual_duration = base_duration * (0.5 + duration_multiplier)
        
        return actual_duration
    
    def _count_student_responses(self, student_attention_data: List[Any]) -> int:
        """统计学生响应数量"""
        if not student_attention_data:
            return 0
        
        # 模拟学生响应统计
        # 实际实现中会基于学生的举手、发言等行为
        active_students = 0
        for student_data in student_attention_data:
            if hasattr(student_data, 'behavior'):
                if student_data.behavior in ['raising_hand', 'discussing']:
                    active_students += 1
            elif hasattr(student_data, 'participation_level'):
                if student_data.participation_level in ['active', 'very_active']:
                    active_students += 1
        
        # 如果没有具体数据，基于学生数量估算
        if active_students == 0:
            total_students = len(student_attention_data)
            response_rate = np.random.uniform(0.1, 0.4)  # 10%-40%的响应率
            active_students = int(total_students * response_rate)
        
        return active_students
    
    def _count_teacher_questions(self, teacher_behavior: TeacherBehaviorData,
                               audio_features: Optional[Dict[str, Any]]) -> int:
        """统计教师提问数量"""
        # 基于教师行为和语音特征估算提问数量
        if teacher_behavior.behavior == TeachingBehavior.QUESTIONING:
            return np.random.randint(1, 4)  # 1-3个问题
        elif teacher_behavior.behavior == TeachingBehavior.INTERACTING:
            return np.random.randint(0, 2)  # 0-1个问题
        elif teacher_behavior.behavior == TeachingBehavior.LECTURING:
            enthusiasm = teacher_behavior.voice_features.get('enthusiasm', 0.5)
            if enthusiasm > 0.7:
                return np.random.randint(0, 2)  # 可能有互动问题
        
        return 0
    
    def _assess_interaction_quality(self, teacher_behavior: TeacherBehaviorData,
                                  student_attention_data: List[Any],
                                  duration: float) -> InteractionQuality:
        """评估互动质量"""
        # 教师表现指标
        teacher_score = 0
        
        # 手势表现
        gesture_intensity = teacher_behavior.gesture_data.get('intensity', 0.5)
        if gesture_intensity > 0.6:
            teacher_score += 0.2
        
        # 语音表现
        voice_quality = teacher_behavior.voice_features.get('voice_quality', 0.5)
        voice_enthusiasm = teacher_behavior.voice_features.get('enthusiasm', 0.5)
        teacher_score += (voice_quality + voice_enthusiasm) * 0.15
        
        # 行为适当性
        appropriate_behaviors = [
            TeachingBehavior.QUESTIONING,
            TeachingBehavior.INTERACTING,
            TeachingBehavior.DEMONSTRATING
        ]
        if teacher_behavior.behavior in appropriate_behaviors:
            teacher_score += 0.2
        
        # 学生参与度
        student_score = 0
        if student_attention_data:
            # 计算平均专注度
            attention_scores = []
            for student_data in student_attention_data:
                if hasattr(student_data, 'attention_score'):
                    attention_scores.append(student_data.attention_score)
                elif hasattr(student_data, 'participation_score'):
                    attention_scores.append(student_data.participation_score)
            
            if attention_scores:
                avg_attention = np.mean(attention_scores)
                student_score = avg_attention / 100.0
        
        # 时长适当性
        duration_score = 0
        if 30 <= duration <= 300:  # 30秒到5分钟为合适范围
            duration_score = 0.2
        elif duration > 300:
            duration_score = max(0, 0.2 - (duration - 300) / 600)  # 超时扣分
        
        # 综合质量分数
        overall_score = teacher_score + student_score * 0.4 + duration_score
        
        # 确定质量等级
        if overall_score >= 0.85:
            return InteractionQuality.EXCELLENT
        elif overall_score >= 0.7:
            return InteractionQuality.GOOD
        elif overall_score >= 0.55:
            return InteractionQuality.AVERAGE
        elif overall_score >= 0.4:
            return InteractionQuality.POOR
        else:
            return InteractionQuality.VERY_POOR
    
    def _calculate_engagement_score(self, student_attention_data: List[Any],
                                  student_response_count: int) -> float:
        """计算参与度分数"""
        if not student_attention_data:
            return 0.0
        
        total_students = len(student_attention_data)
        
        # 基础参与度（基于响应学生比例）
        response_rate = student_response_count / total_students if total_students > 0 else 0
        base_engagement = response_rate * 60  # 最高60分
        
        # 专注度加成
        attention_bonus = 0
        attention_scores = []
        for student_data in student_attention_data:
            if hasattr(student_data, 'attention_score'):
                attention_scores.append(student_data.attention_score)
        
        if attention_scores:
            avg_attention = np.mean(attention_scores)
            attention_bonus = (avg_attention / 100) * 40  # 最高40分
        
        engagement_score = base_engagement + attention_bonus
        return min(100.0, max(0.0, engagement_score))
    
    def _calculate_effectiveness_score(self, interaction_quality: InteractionQuality,
                                     engagement_score: float, duration: float) -> float:
        """计算有效性分数"""
        # 质量分数
        quality_scores = {
            InteractionQuality.EXCELLENT: 100,
            InteractionQuality.GOOD: 80,
            InteractionQuality.AVERAGE: 60,
            InteractionQuality.POOR: 40,
            InteractionQuality.VERY_POOR: 20
        }
        quality_score = quality_scores.get(interaction_quality, 60)
        
        # 参与度权重
        engagement_weight = 0.4
        quality_weight = 0.6
        
        # 时长调整因子
        duration_factor = 1.0
        if duration < 15:  # 太短
            duration_factor = 0.7
        elif duration > 600:  # 太长
            duration_factor = 0.8
        
        effectiveness = (
            quality_score * quality_weight +
            engagement_score * engagement_weight
        ) * duration_factor
        
        return min(100.0, max(0.0, effectiveness))
    
    def _update_trackers(self, teacher_id: str, interaction_type: str,
                        question_count: int, response_count: int):
        """更新跟踪器"""
        self.question_tracker[teacher_id] += question_count
        self.response_tracker[teacher_id] += response_count


class TeachingQualityService:
    """教学质量评估服务"""
    
    def __init__(self):
        self.behavior_analyzer = TeacherBehaviorAnalyzer()
        self.interaction_analyzer = InteractionAnalyzer()
        
        # 数据存储
        self.behavior_data: Dict[str, List[TeacherBehaviorData]] = defaultdict(list)
        self.interaction_data: Dict[str, List[InteractionData]] = defaultdict(list)
        self.style_analyses: Dict[str, List[TeachingStyleAnalysis]] = defaultdict(list)
        self.quality_reports: Dict[str, List[TeachingQualityReport]] = defaultdict(list)
        
        # 服务状态
        self._running = False
        self._analysis_task = None
        self.analysis_interval = 60.0  # 1分钟分析一次
        
        # 统计信息
        self.stats = {
            'total_analyses': 0,
            'active_teachers': 0,
            'average_teaching_quality': 0.0,
            'behavior_distribution': defaultdict(int)
        }
    
    async def start_service(self):
        """启动服务"""
        if self._running:
            return
        
        self._running = True
        self._analysis_task = asyncio.create_task(self._analysis_loop())
        logger.info("Teaching quality service started")
    
    async def stop_service(self):
        """停止服务"""
        self._running = False
        if self._analysis_task:
            self._analysis_task.cancel()
            try:
                await self._analysis_task
            except asyncio.CancelledError:
                pass
        logger.info("Teaching quality service stopped")
    
    async def _analysis_loop(self):
        """分析循环"""
        while self._running:
            try:
                await self._periodic_analysis()
                await asyncio.sleep(self.analysis_interval)
            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Error in teaching quality analysis loop: {e}")
                await asyncio.sleep(30.0)
    
    async def _periodic_analysis(self):
        """周期性分析"""
        # 清理过期数据
        cutoff_time = datetime.now() - timedelta(hours=24)
        
        for teacher_id in list(self.behavior_data.keys()):
            self.behavior_data[teacher_id] = [
                data for data in self.behavior_data[teacher_id]
                if data.timestamp > cutoff_time
            ]
            
            if not self.behavior_data[teacher_id]:
                del self.behavior_data[teacher_id]
        
        # 更新统计信息
        self._update_statistics()
    
    def _update_statistics(self):
        """更新统计信息"""
        self.stats['active_teachers'] = len(self.behavior_data)
        
        # 统计行为分布
        behavior_counts = defaultdict(int)
        total_behaviors = 0
        
        for teacher_behaviors in self.behavior_data.values():
            for behavior_data in teacher_behaviors:
                behavior_counts[behavior_data.behavior.value] += 1
                total_behaviors += 1
        
        self.stats['behavior_distribution'] = dict(behavior_counts)
        self.stats['total_analyses'] = total_behaviors
    
    async def process_video_frame(self, frame: np.ndarray, metadata: Dict[str, Any] = None) -> Dict[str, Any]:
        """处理视频帧进行教学质量分析"""
        try:
            camera_id = metadata.get('camera_id', 'unknown') if metadata else 'unknown'
            frame_timestamp = datetime.fromisoformat(metadata.get('frame_timestamp')) if metadata and metadata.get('frame_timestamp') else datetime.now()
            
            # 模拟教师检测和分析
            teacher_analysis = await self._analyze_teacher_in_frame(frame, camera_id, frame_timestamp)
            
            # 模拟学生注意力数据
            student_attention_data = self._generate_mock_student_attention(frame)
            
            # 分析师生互动
            interaction_analysis = None
            if teacher_analysis:
                interaction_analysis = await self._analyze_interaction_in_frame(
                    teacher_analysis, student_attention_data
                )
            
            return {
                "algorithm": "teaching_quality",
                "camera_id": camera_id,
                "frame_timestamp": frame_timestamp.isoformat(),
                "processing_timestamp": datetime.now().isoformat(),
                "results": {
                    "teacher_analysis": teacher_analysis,
                    "interaction_analysis": interaction_analysis,
                    "student_engagement": {
                        "total_students": len(student_attention_data),
                        "average_attention": np.mean([s.get('attention_score', 70) for s in student_attention_data]),
                        "active_students": sum(1 for s in student_attention_data if s.get('attention_score', 70) > 80)
                    },
                    "teaching_effectiveness": self._calculate_teaching_effectiveness(
                        teacher_analysis, interaction_analysis, student_attention_data
                    )
                },
                "confidence": 0.78,
                "processing_time": 0.25
            }
            
        except Exception as e:
            logger.error(f"教学质量分析处理视频帧失败: {e}")
            return {
                "algorithm": "teaching_quality",
                "camera_id": metadata.get('camera_id', 'unknown') if metadata else 'unknown',
                "error": str(e),
                "processing_timestamp": datetime.now().isoformat()
            }
    
    async def _analyze_teacher_in_frame(self, frame: np.ndarray, camera_id: str, timestamp: datetime) -> Optional[Dict[str, Any]]:
        """分析帧中的教师"""
        # 模拟教师检测
        height, width = frame.shape[:2]
        
        # 假设教师在讲台区域（图像上方1/3区域）
        teacher_bbox = (width//4, 0, width//2, height//3)
        teacher_id = f"teacher_{camera_id}"
        
        # 分析教师行为
        behavior_data = await self.behavior_analyzer.analyze_teacher_behavior(
            frame, teacher_bbox, teacher_id
        )
        
        # 存储行为数据
        self.behavior_data[teacher_id].append(behavior_data)
        
        # 保持最近1000条记录
        if len(self.behavior_data[teacher_id]) > 1000:
            self.behavior_data[teacher_id] = self.behavior_data[teacher_id][-1000:]
        
        return {
            "teacher_id": teacher_id,
            "behavior": behavior_data.behavior.value,
            "gesture_data": behavior_data.gesture_data,
            "facial_expression": behavior_data.facial_expression,
            "movement_data": behavior_data.movement_data,
            "voice_features": behavior_data.voice_features,
            "fatigue_level": behavior_data.fatigue_level.value,
            "confidence": behavior_data.confidence
        }
    
    def _generate_mock_student_attention(self, frame: np.ndarray) -> List[Dict[str, Any]]:
        """生成模拟学生注意力数据"""
        # 模拟15-30个学生
        num_students = np.random.randint(15, 31)
        student_data = []
        
        for i in range(num_students):
            attention_score = np.random.uniform(40, 95)
            participation_level = "active" if attention_score > 80 else "moderate" if attention_score > 60 else "low"
            
            student = {
                "student_id": f"student_{i}",
                "attention_score": attention_score,
                "participation_level": participation_level,
                "behavior": np.random.choice(["listening", "taking_notes", "discussing", "distracted"], 
                                           p=[0.5, 0.3, 0.1, 0.1])
            }
            student_data.append(student)
        
        return student_data
    
    async def _analyze_interaction_in_frame(self, teacher_analysis: Dict[str, Any], 
                                          student_attention_data: List[Dict[str, Any]]) -> Dict[str, Any]:
        """分析帧中的师生互动"""
        teacher_id = teacher_analysis["teacher_id"]
        
        # 重建TeacherBehaviorData对象
        behavior_data = TeacherBehaviorData(
            teacher_id=teacher_id,
            timestamp=datetime.now(),
            behavior=TeachingBehavior(teacher_analysis["behavior"]),
            gesture_data=teacher_analysis["gesture_data"],
            facial_expression=teacher_analysis["facial_expression"],
            movement_data=teacher_analysis["movement_data"],
            voice_features=teacher_analysis["voice_features"],
            fatigue_level=FatigueLevel(teacher_analysis["fatigue_level"]),
            confidence=teacher_analysis["confidence"]
        )
        
        # 转换学生数据格式
        student_objects = []
        for student_data in student_attention_data:
            student_obj = type('StudentData', (), student_data)()
            student_objects.append(student_obj)
        
        # 分析互动
        interaction_data = await self.interaction_analyzer.analyze_interaction(
            teacher_id, behavior_data, student_objects
        )
        
        # 存储互动数据
        self.interaction_data[teacher_id].append(interaction_data)
        
        return {
            "interaction_id": interaction_data.interaction_id,
            "interaction_type": interaction_data.interaction_type,
            "duration": interaction_data.duration,
            "student_response_count": interaction_data.student_response_count,
            "teacher_question_count": interaction_data.teacher_question_count,
            "interaction_quality": interaction_data.interaction_quality.value,
            "engagement_score": interaction_data.engagement_score,
            "effectiveness_score": interaction_data.effectiveness_score
        }
    
    def _calculate_teaching_effectiveness(self, teacher_analysis: Optional[Dict[str, Any]], 
                                        interaction_analysis: Optional[Dict[str, Any]],
                                        student_attention_data: List[Dict[str, Any]]) -> Dict[str, Any]:
        """计算教学有效性"""
        effectiveness_score = 0.0
        
        # 教师表现评分 (40%)
        if teacher_analysis:
            teacher_score = 0
            
            # 行为适当性
            appropriate_behaviors = ["lecturing", "questioning", "demonstrating", "interacting"]
            if teacher_analysis["behavior"] in appropriate_behaviors:
                teacher_score += 25
            
            # 疲劳度影响
            fatigue_penalties = {
                "very_low": 0, "low": -2, "medium": -5, "high": -10, "very_high": -15
            }
            teacher_score += fatigue_penalties.get(teacher_analysis["fatigue_level"], -5)
            
            # 手势表现
            gesture_intensity = teacher_analysis["gesture_data"].get("intensity", 0.5)
            teacher_score += gesture_intensity * 10
            
            # 语音质量
            voice_quality = teacher_analysis["voice_features"].get("voice_quality", 0.5)
            teacher_score += voice_quality * 5
            
            effectiveness_score += max(0, min(40, teacher_score))
        
        # 互动质量评分 (30%)
        if interaction_analysis:
            interaction_score = 0
            
            quality_scores = {
                "excellent": 30, "good": 24, "average": 18, "poor": 12, "very_poor": 6
            }
            interaction_score = quality_scores.get(interaction_analysis["interaction_quality"], 15)
            
            effectiveness_score += interaction_score
        
        # 学生参与度评分 (30%)
        if student_attention_data:
            avg_attention = np.mean([s.get('attention_score', 70) for s in student_attention_data])
            participation_score = (avg_attention / 100) * 30
            effectiveness_score += participation_score
        
        # 确定等级
        if effectiveness_score >= 85:
            effectiveness_level = "excellent"
        elif effectiveness_score >= 75:
            effectiveness_level = "good"
        elif effectiveness_score >= 65:
            effectiveness_level = "average"
        elif effectiveness_score >= 50:
            effectiveness_level = "poor"
        else:
            effectiveness_level = "very_poor"
        
        return {
            "effectiveness_score": effectiveness_score,
            "effectiveness_level": effectiveness_level,
            "teacher_performance": effectiveness_score * 0.4 if teacher_analysis else 0,
            "interaction_quality": effectiveness_score * 0.3 if interaction_analysis else 0,
            "student_engagement": effectiveness_score * 0.3 if student_attention_data else 0
        }


# 全局教学质量服务实例
teaching_quality_service = TeachingQualityService()